/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var levelOrder = function (root) {
  // 迭代实现

  let ans = []
  let front = [root]
  let count = 1


  while (front.length > 0) {
    let tmpCount = count
    count = 0
    let ansArr = []
    while (tmpCount > 0) {
      let tmp = front.shift()
      ansArr.push(tmp.val)
      if (tmp.left) {
        front.unshift(tmp.left)
        count++
      }
      if (tmp.right) {
        front.unshift(tmp.right)
        count++
      }
      tmpCount--
    }
    ans = ans.push(ansArr)
  }

  return ans

};